package com.jd.search.dao;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.highlight.HighlightField;
import org.springframework.stereotype.Repository;
import com.jd.search.pojo.Goods;
import com.jd.search.pojo.SearchResult;

@Repository(value="searchDao")
public class SearchDaoImpl implements SearchDao {
	
	public SearchResult searchGoods(String keywords, int page, int rows) throws Exception {
		SearchResult results = new SearchResult();
		TransportClient client = TransportClient
				.builder()
				.build()
				.addTransportAddress(
						new InetSocketTransportAddress(InetAddress
								.getByName("192.168.19.180"), 9300));
		SearchResponse response = client
				.prepareSearch()
				.setIndices("jd")
				.setTypes("goods")
				.setQuery(
						QueryBuilders.multiMatchQuery(keywords, "category_name",
								"title", "sell_point", "goods_desc"))
				.setFrom((page-1)*rows)
				.setSize(rows)
				.setFetchSource(
						new String[] { "id", "title", "sell_point", "image",
								"category_name","price" }, null)
				.addHighlightedField("title")
				.setHighlighterPreTags("<span style=\"color:red\">")
				.setHighlighterPostTags("</span>").execute().actionGet();

		SearchHits searchHits = response.getHits();
		SearchHit[] hits = searchHits.getHits();
		List<Goods> goodses = new ArrayList<Goods>();
		for (int i = 0; i < hits.length; i++) {
			SearchHit hit = hits[i];
			Map<String, Object> doc = hit.getSource();
			Goods goods = new Goods();
			goods.setId(doc.get("id").toString());
			goods.setCategory_name((String)doc.get("category_name"));
			goods.setImage((String)doc.get("image"));
			goods.setPrice(Long.parseLong(doc.get("price").toString()));
			goods.setSell_point((String)doc.get("sell_point"));

			Map<String, HighlightField> highlightFields = hit
					.getHighlightFields();
			HighlightField title = highlightFields.get("title");
			if(title != null && title.getFragments()!=null){
				Text[] fragments = title.getFragments();
				goods.setTitle(fragments[0].string());
			}else{
				goods.setTitle((String)doc.get("title"));
			}
			goodses.add(goods);
		}
		results.setGoods(goodses);
		results.setCount(searchHits.getTotalHits());
		
		client.close();
		return results;
	}

}
